<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Managing files &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../index.html" />
    <link rel="up" title="Using Django" href="index.html" />
    <link rel="next" title="Testing in Django" href="testing/index.html" />
    <link rel="prev" title="Migrations" href="migrations.html" />



 
<script type="text/javascript" src="../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="migrations.html" title="Migrations">previous</a>
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="testing/index.html" title="Testing in Django">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-files">
            
  <div class="section" id="s-managing-files">
<span id="managing-files"></span><h1>Managing files<a class="headerlink" href="#managing-files" title="Permalink to this headline">¶</a></h1>
<p>This document describes Django&#8217;s file access APIs for files such as those
uploaded by a user. The lower level APIs are general enough that you could use
them for other purposes. If you want to handle &#8220;static files&#8221; (JS, CSS, etc),
see <a class="reference internal" href="../howto/static-files/index.html"><em>Managing static files (CSS, images)</em></a>.</p>
<p>By default, Django stores files locally, using the <a class="reference internal" href="../ref/settings.html#std:setting-MEDIA_ROOT"><tt class="xref std std-setting docutils literal"><span class="pre">MEDIA_ROOT</span></tt></a> and
<a class="reference internal" href="../ref/settings.html#std:setting-MEDIA_URL"><tt class="xref std std-setting docutils literal"><span class="pre">MEDIA_URL</span></tt></a> settings. The examples below assume that you&#8217;re using these
defaults.</p>
<p>However, Django provides ways to write custom <a class="reference internal" href="#file-storage">file storage systems</a> that
allow you to completely customize where and how Django stores files. The
second half of this document describes how these storage systems work.</p>
<div class="section" id="s-using-files-in-models">
<span id="using-files-in-models"></span><h2>Using files in models<a class="headerlink" href="#using-files-in-models" title="Permalink to this headline">¶</a></h2>
<p>When you use a <a class="reference internal" href="../ref/models/fields.html#django.db.models.FileField" title="django.db.models.FileField"><tt class="xref py py-class docutils literal"><span class="pre">FileField</span></tt></a> or
<a class="reference internal" href="../ref/models/fields.html#django.db.models.ImageField" title="django.db.models.ImageField"><tt class="xref py py-class docutils literal"><span class="pre">ImageField</span></tt></a>, Django provides a set of APIs you can use
to deal with that file.</p>
<p>Consider the following model, using an <a class="reference internal" href="../ref/models/fields.html#django.db.models.ImageField" title="django.db.models.ImageField"><tt class="xref py py-class docutils literal"><span class="pre">ImageField</span></tt></a> to
store a photo:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">255</span><span class="p">)</span>
    <span class="n">price</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DecimalField</span><span class="p">(</span><span class="n">max_digits</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">decimal_places</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
    <span class="n">photo</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ImageField</span><span class="p">(</span><span class="n">upload_to</span><span class="o">=</span><span class="s">&#39;cars&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Any <tt class="docutils literal"><span class="pre">Car</span></tt> instance will have a <tt class="docutils literal"><span class="pre">photo</span></tt> attribute that you can use to get at
the details of the attached photo:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">car</span> <span class="o">=</span> <span class="n">Car</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;57 Chevy&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span>
<span class="go">&lt;ImageFieldFile: chevy.jpg&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">name</span>
<span class="go">u&#39;cars/chevy.jpg&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">path</span>
<span class="go">u&#39;/media/cars/chevy.jpg&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">url</span>
<span class="go">u&#39;http://media.example.com/cars/chevy.jpg&#39;</span>
</pre></div>
</div>
<p>This object &#8211; <tt class="docutils literal"><span class="pre">car.photo</span></tt> in the example &#8211; is a <tt class="docutils literal"><span class="pre">File</span></tt> object, which means
it has all the methods and attributes described below.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The file is saved as part of saving the model in the database, so the actual
file name used on disk cannot be relied on until after the model has been
saved.</p>
</div>
<p>For example, you can change the file name by setting the file&#8217;s
<a class="reference internal" href="../ref/files/file.html#django.core.files.File.name" title="django.core.files.File.name"><tt class="xref py py-attr docutils literal"><span class="pre">name</span></tt></a> to a path relative to the file storage&#8217;s
location (<a class="reference internal" href="../ref/settings.html#std:setting-MEDIA_ROOT"><tt class="xref std std-setting docutils literal"><span class="pre">MEDIA_ROOT</span></tt></a> if you are using the default
<a class="reference internal" href="../ref/files/storage.html#django.core.files.storage.FileSystemStorage" title="django.core.files.storage.FileSystemStorage"><tt class="xref py py-class docutils literal"><span class="pre">FileSystemStorage</span></tt></a>):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">os</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">initial_path</span> <span class="o">=</span> <span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">path</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s">&#39;cars/chevy_ii.jpg&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">new_path</span> <span class="o">=</span> <span class="n">settings</span><span class="o">.</span><span class="n">MEDIA_ROOT</span> <span class="o">+</span> <span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">name</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c"># Move the file on the filesystem</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">rename</span><span class="p">(</span><span class="n">initial_path</span><span class="p">,</span> <span class="n">new_path</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">path</span>
<span class="go">&#39;/media/cars/chevy_ii.jpg&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">car</span><span class="o">.</span><span class="n">photo</span><span class="o">.</span><span class="n">path</span> <span class="o">==</span> <span class="n">new_path</span>
<span class="go">True</span>
</pre></div>
</div>
</div>
<div class="section" id="s-the-file-object">
<span id="the-file-object"></span><h2>The <tt class="docutils literal"><span class="pre">File</span></tt> object<a class="headerlink" href="#the-file-object" title="Permalink to this headline">¶</a></h2>
<p>Internally, Django uses a <a class="reference internal" href="../ref/files/file.html#django.core.files.File" title="django.core.files.File"><tt class="xref py py-class docutils literal"><span class="pre">django.core.files.File</span></tt></a> instance any time it
needs to represent a file. This object is a thin wrapper around Python&#8217;s
<a class="reference external" href="http://docs.python.org/library/stdtypes.html#bltin-file-objects">built-in file object</a> with some Django-specific additions.</p>
<p>Most of the time you&#8217;ll simply use a <tt class="docutils literal"><span class="pre">File</span></tt> that Django&#8217;s given you (i.e. a
file attached to a model as above, or perhaps an uploaded file).</p>
<p>If you need to construct a <tt class="docutils literal"><span class="pre">File</span></tt> yourself, the easiest way is to create one
using a Python built-in <tt class="docutils literal"><span class="pre">file</span></tt> object:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.files</span> <span class="kn">import</span> <span class="n">File</span>

<span class="go"># Create a Python file object using open()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s">&#39;/tmp/hello.world&#39;</span><span class="p">,</span> <span class="s">&#39;w&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">myfile</span> <span class="o">=</span> <span class="n">File</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
</pre></div>
</div>
<p>Now you can use any of the documented attributes and methods
of the <a class="reference internal" href="../ref/files/file.html#django.core.files.File" title="django.core.files.File"><tt class="xref py py-class docutils literal"><span class="pre">File</span></tt></a> class.</p>
<p>Be aware that files created in this way are not automatically closed.
The following approach may be used to close files automatically:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.files</span> <span class="kn">import</span> <span class="n">File</span>

<span class="go"># Create a Python file object using open() and the with statement</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">&#39;/tmp/hello.world&#39;</span><span class="p">,</span> <span class="s">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">myfile</span> <span class="o">=</span> <span class="n">File</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">myfile</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s">&#39;Hello World&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">myfile</span><span class="o">.</span><span class="n">closed</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">closed</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Closing files is especially important when accessing file fields in a loop
over a large number of objects. If files are not manually closed after
accessing them, the risk of running out of file descriptors may arise. This
may lead to the following error:</p>
<div class="highlight-python"><div class="highlight"><pre>IOError: [Errno 24] Too many open files
</pre></div>
</div>
</div>
<div class="section" id="s-file-storage">
<span id="file-storage"></span><h2>File storage<a class="headerlink" href="#file-storage" title="Permalink to this headline">¶</a></h2>
<p>Behind the scenes, Django delegates decisions about how and where to store files
to a file storage system. This is the object that actually understands things
like file systems, opening and reading files, etc.</p>
<p>Django&#8217;s default file storage is given by the <a class="reference internal" href="../ref/settings.html#std:setting-DEFAULT_FILE_STORAGE"><tt class="xref std std-setting docutils literal"><span class="pre">DEFAULT_FILE_STORAGE</span></tt></a>
setting; if you don&#8217;t explicitly provide a storage system, this is the one that
will be used.</p>
<p>See below for details of the built-in default file storage system, and see
<a class="reference internal" href="../howto/custom-file-storage.html"><em>Writing a custom storage system</em></a> for information on writing your own file
storage system.</p>
<div class="section" id="s-storage-objects">
<span id="storage-objects"></span><h3>Storage objects<a class="headerlink" href="#storage-objects" title="Permalink to this headline">¶</a></h3>
<p>Though most of the time you&#8217;ll want to use a <tt class="docutils literal"><span class="pre">File</span></tt> object (which delegates to
the proper storage for that file), you can use file storage systems directly.
You can create an instance of some custom file storage class, or &#8211; often more
useful &#8211; you can use the global default storage system:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.files.storage</span> <span class="kn">import</span> <span class="n">default_storage</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.files.base</span> <span class="kn">import</span> <span class="n">ContentFile</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">path</span> <span class="o">=</span> <span class="n">default_storage</span><span class="o">.</span><span class="n">save</span><span class="p">(</span><span class="s">&#39;/path/to/file&#39;</span><span class="p">,</span> <span class="n">ContentFile</span><span class="p">(</span><span class="s">&#39;new content&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">path</span>
<span class="go">u&#39;/path/to/file&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">default_storage</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
<span class="go">11</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">default_storage</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">path</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="go">&#39;new content&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">default_storage</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">default_storage</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
<span class="go">False</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="../ref/files/storage.html"><em>File storage API</em></a> for the file storage API.</p>
</div>
<div class="section" id="s-the-built-in-filesystem-storage-class">
<span id="s-builtin-fs-storage"></span><span id="the-built-in-filesystem-storage-class"></span><span id="builtin-fs-storage"></span><h3>The built-in filesystem storage class<a class="headerlink" href="#the-built-in-filesystem-storage-class" title="Permalink to this headline">¶</a></h3>
<p>Django ships with a <a class="reference internal" href="../ref/files/storage.html#django.core.files.storage.FileSystemStorage" title="django.core.files.storage.FileSystemStorage"><tt class="xref py py-class docutils literal"><span class="pre">django.core.files.storage.FileSystemStorage</span></tt></a> class
which implements basic local filesystem file storage.</p>
<p>For example, the following code will store uploaded files under
<tt class="docutils literal"><span class="pre">/media/photos</span></tt> regardless of what your <a class="reference internal" href="../ref/settings.html#std:setting-MEDIA_ROOT"><tt class="xref std std-setting docutils literal"><span class="pre">MEDIA_ROOT</span></tt></a> setting is:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">django.core.files.storage</span> <span class="kn">import</span> <span class="n">FileSystemStorage</span>

<span class="n">fs</span> <span class="o">=</span> <span class="n">FileSystemStorage</span><span class="p">(</span><span class="n">location</span><span class="o">=</span><span class="s">&#39;/media/photos&#39;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="o">...</span>
    <span class="n">photo</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ImageField</span><span class="p">(</span><span class="n">storage</span><span class="o">=</span><span class="n">fs</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="../howto/custom-file-storage.html"><em>Custom storage systems</em></a> work the same way:
you can pass them in as the <tt class="docutils literal"><span class="pre">storage</span></tt> argument to a
<a class="reference internal" href="../ref/models/fields.html#django.db.models.FileField" title="django.db.models.FileField"><tt class="xref py py-class docutils literal"><span class="pre">FileField</span></tt></a>.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Managing files</a><ul>
<li><a class="reference internal" href="#using-files-in-models">Using files in models</a></li>
<li><a class="reference internal" href="#the-file-object">The <tt class="docutils literal"><span class="pre">File</span></tt> object</a></li>
<li><a class="reference internal" href="#file-storage">File storage</a><ul>
<li><a class="reference internal" href="#storage-objects">Storage objects</a></li>
<li><a class="reference internal" href="#the-built-in-filesystem-storage-class">The built-in filesystem storage class</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="migrations.html">Migrations</a></li>
    
    
      <li>Next: <a href="testing/index.html">Testing in Django</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="index.html">Using Django</a>
        
        <ul><li>Managing files</li></ul>
        </li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../_sources/topics/files.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="migrations.html" title="Migrations">previous</a>
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="testing/index.html" title="Testing in Django">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>